<template>
  <div class="container" v-if="currentParams">
    <div class="flx-center" style="margin-bottom: 10px">
      <el-button
        type="primary"
        :icon="Back"
        size="small"
        class="arrowBtn Previous"
        aria-label="Previous"
        @click="changeParamsIndex(-1)"
      />
      <div class="chartTitle">{{ currentParams.title }}</div>
      <el-button
        type="primary"
        :icon="Right"
        size="small"
        class="arrowBtn Next"
        aria-label="Next"
        @click="changeParamsIndex(1)"
      />
    </div>
    <swiper
      :modules="modules"
      :loop="true"
      :slides-per-view="1"
      :space-between="50"
      :autoplay="autoplayConfig"
      :navigation="navigation"
      @swiper="onSwiper"
      @slide-change="onSlideChange"
      class="swiperBox"
    >
      <swiper-slide v-for="(slide, slideIndex) in slicedData" :key="slideIndex">
        <el-row :gutter="10">
          <el-col :span="8" v-for="(item, k) in slide.data" :key="k">
            <div class="dataBgH mb12 hasHover" @click="handleClick(item.name, item.flag)">
              <i class="hoverIcon"></i>
              <el-tooltip class="box-item" effect="customized" :content="item.name" placement="top-start">
                <div class="dataName mb8 multiline-ellipsis" style="text-align: center" v-html="formatName(item.name, 4)"></div>
              </el-tooltip>
              <div class="flx-center">
                <span class="dataValue">{{ item.value }}</span>
                <i :class="getArrowClass(item.status as any)" class="ml4"></i>
              </div>
            </div>
          </el-col>
        </el-row>
      </swiper-slide>
      <div class="swiper-button-prev"></div>
      <div class="swiper-button-next"></div>
    </swiper>
  </div>
</template>

<script lang="ts" setup>
import { Autoplay, Pagination, Navigation, Scrollbar } from "swiper/modules";
import { computed, ref, watch, onMounted } from "vue";
import { Right, Back } from "@element-plus/icons-vue";
import { Swiper, SwiperSlide } from "swiper/vue";
import type { Swiper as SwiperType } from "swiper";
import "swiper/css";
import "swiper/css/navigation";
import { getAuthTopApi } from "@/api/modules/datascreenV2";

interface DataItem {
  name: string;
  value: number;
  status: "up" | "down";
}

interface Params {
  title: string;
  data: DataItem[];
}

const emit = defineEmits(["clickEvent"]);

const params = ref<Params[] | any>([]);
const swiperInstance = ref<SwiperType | null>(null);
const isAutoplay = ref(true);

// 方法：将字符串按指定长度插入换行符
const formatName = (str: string, every: number): string => {
  if (!str) return "<br><br>";
  if (str.length <= every) return "<br>" + str + "<br>";
  // console.log(str, str.length, every);
  const regex = new RegExp(`.{1,${every}}`, "g");
  return str.match(regex)?.join("<br>") || "";
};

const currentSlideIndex = ref(0);
const currentParamsIndex = ref(0);
const autoplayConfig = computed(() => ({
  delay: 4000,
  disableOnInteraction: true,
  pauseOnMouseEnter: true
}));

const currentParams = computed(() => params.value[currentParamsIndex.value]);
const slicedData = computed(() => {
  const currentData = currentParams.value.data;
  const slideSize = 9; // Number of items per slide
  const totalSlides = Math.ceil(currentData.length / slideSize);
  let slides = [] as any;

  for (let i = 0; i < totalSlides; i++) {
    const start = i * slideSize;
    const end = start + slideSize;
    const slideData = currentData.slice(start, end);
    slides.push({ data: slideData });
  }

  return slides;
});
const handleClick = (name: string, flag: string) => {
  emit("clickEvent", "网络运行情况", flag);
};
const getArrowClass = computed(() => (status: "up" | "down") => (status === "up" ? "arrowUp" : "arrowDown"));

const changeParamsIndex = (step: number) => {
  currentParamsIndex.value = (currentParamsIndex.value + step + params.value.length) % params.value.length;
  currentSlideIndex.value = 0;
  if (swiperInstance.value) {
    swiperInstance.value.slideTo(0);
    isAutoplay.value = true;
    swiperInstance.value.autoplay.start();
  }
};

const modules = [Autoplay, Pagination, Navigation, Scrollbar];
const navigation = ref({
  nextEl: ".swiper-button-next",
  prevEl: ".swiper-button-prev"
});

const onSwiper = (swiper: SwiperType) => {
  swiperInstance.value = swiper;
};

const onSlideChange = () => {
  if (swiperInstance.value) {
    currentSlideIndex.value = swiperInstance.value.realIndex;
    if (swiperInstance.value.autoplay.running) {
      swiperInstance.value.autoplay.start();
    }
    // isAutoplay.value = false;
    // swiperInstance.value.autoplay.stop();
  }
};

onMounted(async () => {
  const res = await getAuthTopApi();
  params.value = res.data;
  currentParamsIndex.value = 0;
});

// 使用 watch 来处理副作用
watch(
  currentParamsIndex,
  newIndex => {
    currentSlideIndex.value = 0;
    console.log(currentParamsIndex.value + "发生变化" + newIndex + "，重置轮播到第一页");
    if (swiperInstance.value) {
      swiperInstance.value.slideTo(0);
      isAutoplay.value = true;
      swiperInstance.value.autoplay.start();
    }
  },
  { immediate: true }
);

// 监听自动播放状态
watch(isAutoplay, newValue => {
  if (swiperInstance.value) {
    if (newValue) {
      swiperInstance.value.autoplay.start();
    } else {
      swiperInstance.value.autoplay.stop();
    }
  }
});
</script>

<style lang="scss" scoped>
.container {
  position: relative;
  width: 100%;
  height: 100%;
}
.dataBgH {
  padding: 10px 0;
  cursor: pointer;
  background-image: radial-gradient(
    circle at 50% 0%,
    rgb(23 173 255 / 20%) 0%,
    rgb(23 173 255 / 20%) 0%,
    rgb(40 115 255 / 6%) 99%
  );
  &.hasHover:hover {
    position: relative;
    background-image: radial-gradient(
      circle at 50% 0%,
      rgb(23 173 255 / 50%) 0%,
      rgb(23 173 255 / 50%) 0%,
      rgb(40 115 255 / 12%) 99%
    );
    &::before {
      position: absolute;
      top: 0;
      left: 0;
      box-sizing: border-box;
      display: inline-block;
      width: 6px;
      height: 6px;
      content: "";
      border-top: 1px solid #27d7ff;
      border-left: 1px solid #27d7ff;
    }
    &::after {
      position: absolute;
      top: 0;
      right: 0;
      box-sizing: border-box;
      display: inline-block;
      width: 6px;
      height: 6px;
      content: "";
      border-top: 1px solid #27d7ff;
      border-right: 1px solid #27d7ff;
    }
    .hoverIcon {
      &::before {
        position: absolute;
        bottom: 0;
        left: 0;
        box-sizing: border-box;
        display: inline-block;
        width: 6px;
        height: 6px;
        content: "";
        border-bottom: 1px solid #27d7ff;
        border-left: 1px solid #27d7ff;
      }
      &::after {
        position: absolute;
        right: 0;
        bottom: 0;
        box-sizing: border-box;
        display: inline-block;
        width: 6px;
        height: 6px;
        content: "";
        border-right: 1px solid #27d7ff;
        border-bottom: 1px solid #27d7ff;
      }
    }
  }
}
.dataName {
  // font-family: YouSheBiaoTiHei;
  font-family: "Microsoft YaHei";
  font-size: 16px;
  line-height: 20px;
  color: #ffffff;
}
.multiline-ellipsis {
  display: -webkit-box;
  -webkit-box-orient: vertical;
  -webkit-line-clamp: 2;
  overflow: hidden;
  text-overflow: ellipsis;
}
.dataValue {
  min-height: 24px;
  font-family: futura;
  font-size: 20px;
  line-height: 24px;
  color: #00d5ff;
}
.arrowBtn {
  position: absolute;
  box-sizing: border-box;
  width: 10px;
  height: 18px;
  color: #b1d8ff;
  background: rgb(102 226 251 / 8%);
  border: 1px solid rgb(18 142 255 / 40%);
  &.ant-btn-sm {
    border-radius: 0;
  }
}
.arrowBtn:hover {
  color: #00d5ff;
  background-color: rgb(102 226 251 / 30%);
}
.Previous {
  left: 0;
}
.Next {
  right: 0;
}
.swiper-button-prev,
.swiper-button-next {
  width: 1px;
  height: 1px;

  --swiper-navigation-size: 30px;
}
</style>
